import { BaseService, CoolCommException, CoolValidateException } from "@cool-midway/core";
import { Inject, Provide } from "@midwayjs/core";
import { Repository, DataSource, MoreThan } from "typeorm";
import { ProductInfoEntity, ProductStatus } from "../entity/info";
import { InjectEntityModel, InjectDataSource } from "@midwayjs/typeorm";
import { Context } from "@midwayjs/koa";
import { AddProductDTO } from "../dto/info";
import { ProductItemEntity } from "../entity/item";
import { ProductRefundConfigEntity } from "../entity/refund/config";
import { StorageInfoEntity } from "../../storage/entity/info";
import { CommonAuditStatus } from "../../../interface";

@Provide()
export class ProductInfoService extends BaseService {

    @InjectEntityModel(ProductInfoEntity)
    productInfoEntity: Repository<ProductInfoEntity>;

    @InjectEntityModel(ProductItemEntity)
    productItemEntity: Repository<ProductItemEntity>;


    @InjectEntityModel(StorageInfoEntity)
    storageInfoModel: Repository<StorageInfoEntity>

    @InjectEntityModel(ProductRefundConfigEntity)
    refundConfigEntity: Repository<ProductRefundConfigEntity>;

    @InjectDataSource()
    dataSource: DataSource;

    @Inject()
    ctx: Context


    /**
     * 新增产品
     * @param dto 产品DTO
     * @returns 产品信息
     */
    async add(dto: AddProductDTO, source: 'user' | 'storage' = 'user', sourceStorageId?: number, sourceProductId?: number) {
        const {
            name,
            cover,
            content,
            basePrice,
            specs,
            images,
            type,
            productItems = [],
            refundConfigs = [],
        } = dto
        const tenantId = this.ctx.provider?.tenantId

        // 使用事务确保主表与子项一致性
        return await this.dataSource.transaction(async manager => {
            const productInfoRepo = manager.getRepository(ProductInfoEntity)
            const productItemRepo = manager.getRepository(ProductItemEntity)
            const refundConfigRepo = manager.getRepository(ProductRefundConfigEntity)
            const productInfo = await productInfoRepo.save({
                name,
                cover,
                content,
                basePrice,
                specs,
                images,
                type,
                status: ProductStatus.DRAFT,
                tenantId,
                source,
                sourceStorageId,
                sourceProductId,
            })

            const itemsToSave = (productItems || []).map(item => ({
                ...item,
                productId: productInfo.id,
            }))

            const productItemList = itemsToSave.length
                ? await productItemRepo.save(itemsToSave)
                : []

            const refundConfigsToSave = (refundConfigs || []).map(item => ({
                type: item.type,
                value: item.value,
                productId: productInfo.id,
            }))
            const refundConfigList = refundConfigsToSave.length
                ? await refundConfigRepo.save(refundConfigsToSave)
                : []

            return {
                ...productInfo,
                productItems: productItemList,
                refundConfigs: refundConfigList,
            }
        })
    }





    /**
     * 从云仓添加产品
     * @param storageId 云仓产品ID
     * @returns 产品信息
     */
    async addByStorage(storageId: number) {
        if (!storageId) {
            throw new CoolValidateException('请选择要添加至产品的云仓产品')
        }
        // 查询云仓产品信息
        const storageInfo = await this.storageInfoModel.findOne({ where: { id: storageId, status: CommonAuditStatus.APPROVED, expireDate: MoreThan(new Date()) } })
        if (!storageInfo) {
            throw new CoolCommException('云仓产品不存在或已过期')
        }
        // 查询云仓关联产品信息
        const productInfo = await this.productInfoEntity.findOne({ where: { id: storageInfo.productId, status: ProductStatus.ON_SALE } })
        if (!productInfo) {
            throw new CoolCommException('云仓关联产品无效，请联系云仓产品提供方')
        }

        const productItemList = await this.productItemEntity.find({ where: { productId: productInfo.id } })
        const refundConfigList = await this.refundConfigEntity.find({ where: { productId: productInfo.id } })
        // 根据产品信息复制一份到自己站点上'
        return await this.add({
            name: productInfo.name,
            cover: productInfo.cover,
            content: productInfo.content,
            basePrice: productInfo.basePrice,
            specs: productInfo.specs,
            images: productInfo.images,
            type: productInfo.type,
            productItems: productItemList,
            refundConfigs: refundConfigList,
        }, 'storage', storageId, productInfo.id)


    }


    /**
     * 修改产品
     * @param dto 产品DTO
     * @returns 产品信息
     */
    async update(dto: any) {
        const { id, ...rest } = dto;

        if (!id) {
            throw new CoolValidateException('缺少产品ID')
        }

        await this.dataSource.transaction(async manager => {
            const productInfoRepo = manager.getRepository(ProductInfoEntity)
            const storageInfoRepo = manager.getRepository(StorageInfoEntity)

            // 查询产品信息
            const productInfo = await productInfoRepo.findOne({ where: { id } })
            if (!productInfo) {
                throw new CoolCommException('产品不存在')
            }

            // 若为云仓产品，先下架（按原始逻辑仅下架当前产品）
            const isExists = await storageInfoRepo.exists({
                where: { id: productInfo.publishedStorageId, status: CommonAuditStatus.APPROVED, expireDate: MoreThan(new Date()) }
            })
            if (isExists) {
                await productInfoRepo.update(productInfo.id, { status: ProductStatus.DELETE })
            }

            // 更新产品信息（忽略 id 字段）
            await productInfoRepo.update(productInfo.id, rest)
        })

    }


    /**
     * 删除产品
     * @param id 产品ID
     */
    async delete(id: number) {
        if (!id) {
            throw new CoolValidateException('缺少产品ID')
        }

        await this.dataSource.transaction(async manager => {
            const productInfoRepo = manager.getRepository(ProductInfoEntity)
            const storageInfoRepo = manager.getRepository(StorageInfoEntity)
            const productItemRepo = manager.getRepository(ProductItemEntity)
            const refundConfigRepo = manager.getRepository(ProductRefundConfigEntity)

            const productInfo = await productInfoRepo.findOne({ where: { id } })
            if (!productInfo) {
                throw new CoolCommException('产品不存在')
            }

            // 如果产品是云仓产品，则处理关联商户产品并删除云仓记录
            if (productInfo.source === 'storage') {
                // 批量将所有引用该云仓发布ID的商户产品标记为删除
                await productInfoRepo.update({ sourceStorageId: productInfo.publishedStorageId }, { status: ProductStatus.DELETE })
                // 删除云仓产品记录
                await storageInfoRepo.delete({ id: productInfo.publishedStorageId })
            }

            // 先删除关联的子项与退款配置
            await productItemRepo.delete({ productId: id })
            await refundConfigRepo.delete({ productId: id })

            // 最后删除主产品
            await productInfoRepo.delete(id)
        })
    }
}